import config from './config'

const env = process.env.NODE_ENV

/**
 * 检查域名是否合法
 * @param domain 域名
 */
function checkDomain (domain = '') {
  if (!domain.startsWith('http') && !domain.startsWith('https') && !domain.startsWith('ws') && !domain.startsWith('ws')) {
    throw new Error('Domain is invalid, please edit file src/network/config.js.')
  }
}

/**
 * 获取http url
 * @returns {string}
 */
function getHttpUrl () {
  let httpUrl = ''
  if (env !== 'production') {
    httpUrl = `${config.httpDomain}/`
    checkDomain(httpUrl)
  } else {
    httpUrl = `${window.location.origin}/`
  }
  return httpUrl
}

/**
 * 获取ws url
 * @returns {string}
 */
function getWsUrl () {
  let wsUrl = ''
  if (env !== 'production') {
    wsUrl = `${config.wsDomain}/ws`
    checkDomain(wsUrl)
  } else {
    const protocol = window.location.protocol
    const wsProtocol = protocol.startsWith('https') ? 'wss:' : 'ws:'
    wsUrl = `${wsProtocol}//${window.location.host}/ws`
  }
  return wsUrl
}

export { getHttpUrl, getWsUrl }
